<template>
  <div class="flex gap2">
    <ElSelect v-model="seedName" placeholder="模块">
      <ElOption v-for="(seed, seedName) in seedOptions" :label="seed.label" :value="seedName" :key="seedName" />
    </ElSelect>
    <ElSelect v-model="column" placeholder="列">
      <ElOption v-for="(column, columnName) in columnOptions" :label="column.label" :value="columnName" :key="columnName" />
    </ElSelect>
  </div>
</template>
<script setup lang="ts">
  import { ElOption, ElSelect } from 'element-plus';
  import { computed, onMounted, ref, watch } from 'vue';
  import { getSeeds, getSeed } from '@/views/seed-dev';
  import { RelationType } from '@/views/types';
  import { getRefColumns } from '../../utils/SeedUtil';
  import { SeedConfiguration } from '@/views/dev-types';

  const props = defineProps<{seedName?: string, column?: string, type: RelationType}>()
  const emits = defineEmits(['update:seedName', 'update:column'])
  const seedOptions = computed(() => {
    const ret: Record<string, SeedConfiguration> = {}
    const seeds = getSeeds()
    if(props.type === 'belongsTo' || props.type === 'habtm') {
      for(const seedName in seeds) {
        const seed = seeds[seedName]
        if(seed.type !== 'through') ret[seedName] = seed
      }
      return ret
    }

    for(const seedName in seeds) {
      const seed = seeds[seedName]
      const refColumns = getRefColumns(seed)
      if(Object.keys(refColumns).length > 0) ret[seedName] = seed
    }

    return ret
  })  

  const columnOptions = computed(() => {
    if(!seedName.value) return {}

    const seed = getSeed(seedName.value)
    if(props.type === 'belongsTo' || props.type === 'habtm') return {id: seed.columns['id']}

    return getRefColumns(seed)
  })

  const seedName = ref<string>()
  const column = ref<string>()

  function initSeedName() {
    if(props.seedName) {
      seedName.value = props.seedName
    } else {
      const seedNames = Object.keys(seedOptions.value)
      if(seedNames.length === 1) seedName.value = seedNames[0]
    }    
  }

  function initColumn() {
    if(seedName.value) {
      if(props.type === 'belongsTo' || props.type === 'habtm') {
        column.value = 'id'
      } else {
        const seed = seedOptions.value[seedName.value]
        const refColumns = Object.keys(getRefColumns(seed))
        if(refColumns.length === 1) {
          column.value = refColumns[0]
        } else if(props.column && refColumns.includes(props.column)) {
          column.value = props.column
        } else {          
          column.value = void 0
        }
      }
    } else {
      column.value = void 0
    }
  }

  watch(() => props.seedName, (val) => seedName.value = val)
  watch(() => props.column, (val) => column.value = val)

  watch(seedName, (val) => {
    emits('update:seedName', val)
    initColumn()
  })
  watch(column, (val) => emits('update:column', val))

  onMounted(() => {
    initSeedName()
    initColumn()
  })
</script>